package blue.web.dao.service;

import blue.tools.constants.BlueContants;
import blue.commons.enums.GenderEnum;
import blue.elective_result.model.ClassResult;
import blue.elective_result.model.SubjectResult;
import blue.erp.model.BlueClass;
import blue.erp.model.BlueCourse;
import blue.erp.model.SysUser;
import blue.splitclass.model.ElectiveStudentSelected;
import blue.splitclass.model.ElectiveTask;
import blue.tools.commons.BlueStringUtils;
import blue.web.cache.service.RedisService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.raistlic.common.permutation.Combination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * 用户选课后，立即触发缓存计数，每天晚上跑一遍程序，将缓存数据落盘并且校正缓存
 */
@Service
public class ElectiveTaskResultService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private BlueClassService blueClassService;

    @Autowired
    private ElectiveTaskService electiveTaskService;

    @Autowired
    private SysUserService sysUserService;


    public List<ClassResult> getClassResultByTask(Long taskId, SysUser sysUser){
        ElectiveTask electiveTask=electiveTaskService.selectById(taskId,sysUser.getSchoolid());
        if(electiveTask==null || electiveTask.getId()==null || electiveTask.getGradeid()==null){
            return null;
        }

        List<BlueClass> blueClassList=blueClassService.selectClassByGradeId(electiveTask.getGradeid(),electiveTask.getSchoolid(),false);
        if(CollectionUtils.isEmpty(blueClassList)){
            return null;
        }

        List<ClassResult> result=new LinkedList<>();
        for(BlueClass blueClass:blueClassList){
            ClassResult classResult=new ClassResult();
            classResult.setName(blueClass.getName());
            classResult.setTaskId(taskId);
            classResult.setSelectedCount(redisService.getSetSize(String.format("%s_%s_%s_%s",BlueContants.prefix_selected_class,sysUser.getSchoolid(),taskId,blueClass.getId())));
            classResult.setTotalCount(sysUserService.getStudentCountOfClass(blueClass.getId(),blueClass.getSchoolid(),3));
            classResult.setUnSelectedCount(classResult.getTotalCount()-classResult.getSelectedCount());
            classResult.setId(blueClass.getId());
            if(classResult.getTotalCount()!=null && classResult.getTotalCount()>0){
                classResult.setSelectedRatio((float) ((classResult.getSelectedCount()*1.0/classResult.getTotalCount())*100));
            }else {
                classResult.setSelectedRatio((float) 0);
            }
            result.add(classResult);
        }

        Collections.sort(result);
        return result;
    }

    public List<SubjectResult> getSingleSubjectByTask(ElectiveTask electiveTask,SysUser sysUser){

        if(electiveTask==null || electiveTask.getId()==null || StringUtils.isBlank(electiveTask.getCourseIds())){
            return null;
        }

        List<BlueCourse> blueCourseList=JSONArray.parseArray(JSONObject.toJSONString(electiveTask.getList()),BlueCourse.class);

        List<SubjectResult> result=new LinkedList<>();
        for(BlueCourse blueCourse:blueCourseList){
            SubjectResult subjectResult=new SubjectResult();
            subjectResult.setName(blueCourse.getName());
            subjectResult.setTotalCount(redisService.getSetSize(String.format("%s_%s_%s_%s",BlueContants.prefix_selected_oneSubject_total,sysUser.getSchoolid(),electiveTask.getId(),blueCourse.getId())));
            subjectResult.setFemaleCount(redisService.getSetSize(String.format("%s_%s_%s_%s",BlueContants.prefix_selected_oneSubject_male,sysUser.getSchoolid(),electiveTask.getId(),blueCourse.getId())));
            subjectResult.setMaleCount(redisService.getSetSize(String.format("%s_%s_%s_%s",BlueContants.prefix_selected_oneSubject_female,sysUser.getSchoolid(),electiveTask.getId(),blueCourse.getId())));
            result.add(subjectResult);
        }

        return result;
    }

    public List<SubjectResult> getMutilSubjectByTask(Long taskId,SysUser sysUser,int count){

        if(count<=0){
            return null;
        }

        ElectiveTask electiveTask=electiveTaskService.selectById(taskId,sysUser.getSchoolid());
        if(electiveTask==null || electiveTask.getId()==null || StringUtils.isBlank(electiveTask.getCourseIds())){
            return null;
        }

        if(count==1){
            return getSingleSubjectByTask(electiveTask,sysUser);
        }

        List<BlueCourse> blueCourseList=JSONArray.parseArray(JSONObject.toJSONString(electiveTask.getList()),BlueCourse.class);
        HashMap courseMap=new HashMap();
        for(BlueCourse blueCourse:blueCourseList){
            courseMap.put(blueCourse.getId(),blueCourse.getName());
        }

        if(count>blueCourseList.size()){
            count=blueCourseList.size();
        }

        List<SubjectResult> result=new LinkedList<>();
        //获取组合
        Combination<Long> combination = Combination.of(BlueStringUtils.convertString2Num(electiveTask.getCourseIds(),","), count);
        for (List<Long> list : combination) {
             List nameList=new LinkedList();
             for(Long courseId:list){
                 nameList.add(courseMap.get(courseId));
             }

            SubjectResult subjectResult=new SubjectResult();
            subjectResult.setName(StringUtils.join(nameList,","));
            subjectResult.setTotalCount((long) redisService.getSetSinter(String.format("%s_%s_%s",BlueContants.prefix_selected_oneSubject_total,sysUser.getSchoolid(),electiveTask.getId()),list));
            subjectResult.setFemaleCount((long) redisService.getSetSinter(String.format("%s_%s_%s",BlueContants.prefix_selected_oneSubject_male,sysUser.getSchoolid(),electiveTask.getId()),list));
            subjectResult.setMaleCount((long) redisService.getSetSinter(String.format("%s_%s_%s",BlueContants.prefix_selected_oneSubject_female,sysUser.getSchoolid(),electiveTask.getId()),list));
            result.add(subjectResult);

        }

        return result;
    }


    public void saveData(ElectiveStudentSelected electiveStudentSelected, SysUser sysUser){

        if(electiveStudentSelected==null || sysUser==null){
            return;
        }
        //班级选课人数加一
        if(sysUser.getId()!=null){
            redisService.add2Set(String.format("%s_%s_%s_%s",BlueContants.prefix_selected_class,sysUser.getSchoolid(),electiveStudentSelected.getTaskId(),sysUser.getClassIds()),sysUser.getId().toString());
        }

        clearUser(electiveStudentSelected,sysUser);

        //科目结果加一
        if(StringUtils.isNotBlank(electiveStudentSelected.getCourseIds())){
            String[] courseIds=electiveStudentSelected.getCourseIds().split(",");
            for(String courseId:courseIds){
                redisService.add2Set(String.format("%s_%s_%s_%s",BlueContants.prefix_selected_oneSubject_total,sysUser.getSchoolid(),electiveStudentSelected.getTaskId(),courseId),sysUser.getId().toString());

                if(StringUtils.isNotBlank(sysUser.getSex())){
                    if(sysUser.getSex().equalsIgnoreCase(GenderEnum.Male.getValue())){
                        redisService.add2Set(String.format("%s_%s_%s_%s",BlueContants.prefix_selected_oneSubject_male,sysUser.getSchoolid(),electiveStudentSelected.getTaskId(),courseId),sysUser.getId().toString());
                    }else if(sysUser.getSex().equalsIgnoreCase(GenderEnum.Female.getValue())){
                        redisService.add2Set(String.format("%s_%s_%s_%s",BlueContants.prefix_selected_oneSubject_female,sysUser.getSchoolid(),electiveStudentSelected.getTaskId(),courseId),sysUser.getId().toString());
                    }
                }
            }
        }
    }


    public void clearUser(ElectiveStudentSelected electiveStudentSelected, SysUser sysUser){
        ElectiveTask electiveTask=electiveTaskService.selectById(electiveStudentSelected.getTaskId(),sysUser.getSchoolid());
        if(electiveTask==null || electiveTask.getId()==null || StringUtils.isBlank(electiveTask.getCourseIds())){
            return ;
        }
        List<Long> courseList=BlueStringUtils.convertString2Num(electiveTask.getCourseIds(),",");
        for(Long courseId:courseList){
            redisService.remove2Set(String.format("%s_%s_%s_%s",BlueContants.prefix_selected_oneSubject_total,sysUser.getSchoolid(),electiveStudentSelected.getTaskId(),courseId),sysUser.getId().toString());
            redisService.remove2Set(String.format("%s_%s_%s_%s",BlueContants.prefix_selected_oneSubject_male,sysUser.getSchoolid(),electiveStudentSelected.getTaskId(),courseId),sysUser.getId().toString());
            redisService.remove2Set(String.format("%s_%s_%s_%s",BlueContants.prefix_selected_oneSubject_female,sysUser.getSchoolid(),electiveStudentSelected.getTaskId(),courseId),sysUser.getId().toString());
        }

    }

}
